<template>
  <s-clean-layout navbar="none" tabbar="/pages/index/contact">
    <view class="page-container">
      <!-- 固定顶部区域 -->
      <view class="fixed-header">
    <!-- 顶部状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    <!-- 顶部标题栏 -->
    <view class="nav-header">
      <text class="title">联系人</text>
    </view>
      <!-- Tab 标题栏 -->
      <view class="tab-header">
        <view
            class="tab-item"
            :class="{ active: tabIndex === 0 }"
            @tap="changeTab(0)"
        >
          <text>通讯录</text>
        </view>
        <view
            class="tab-item"
            :class="{ active: tabIndex === 1 }"
            @tap="changeTab(1)"
        >
          <text>群组</text>
        </view>
        <view
            class="tab-item"
            :class="{ active: tabIndex === 2 }"
            @tap="changeTab(2)"
        >
          <text>标签</text>
        </view>
      </view>
      </view>
      


      <!-- 可滚动内容区域 -->
      <view class="scrollable-content">
      <view class="content-area">
        <!-- 通讯录内容 -->
        <view v-if="tabIndex === 0" class="address-book">
          <!-- 加载状态 -->
          <view v-if="loading" class="loading-container">
            <text>加载中...</text>
          </view>
          <!-- 空状态 -->
          <view v-if="!loading && (!contactList || contactList.length === 0)" class="empty-container">
            <text>暂无联系人</text>
            <button class="add-btn" @tap="onAddContact">添加联系人</button>
          </view>
          <!-- 列表内容 -->
          <next-indexed-xlist
              v-if="!loading && contactList && contactList.length > 0"
              :dataList="processedContactList"
              :showAvatar="true"
              :nameKey="'name'"
              :phoneKey="'phone'"
              :imgKey="'img'"
              @itemclick="onContactClick"
          />
        </view>
        <!-- 群组内容 -->
        <group-tab v-show="tabIndex === 1" ref="groupTabRef" />
        <!-- 标签内容 -->
        <tag-tab v-show="tabIndex === 2" ref="tagTabRef" />
      </view>
      <!-- 添加悬浮按钮 - 只在通讯录页面显示 -->
      <view v-if="tabIndex === 0" class="floating-btn" @tap="onAddContact">
        <text class="btn-icon">+</text>
        </view>
      </view>
    </view>
  </s-clean-layout>
</template>

<script>
import ContactApi from '@/sheep/api/contact/contact';
import RelationGraph from '@/sheep/components/s-relation-graph/index.vue';
import GroupTab from '@/sheep/components/s-contact-group/group-tab.vue';
import TagTab from '@/sheep/components/s-contact-tag/tag-tab.vue';
import { onMounted } from 'vue'
import { onLaunch, onShow, onError } from '@dcloudio/uni-app';

export default {
  components: {
    RelationGraph,
    GroupTab,
    TagTab
  },
  data() {
    return {
      statusBarHeight: 20, // 状态栏高度
      tabIndex: 0,
      currentTab: 'contact',
      contactList: [], // 原始联系人列表
      loading: true, // 默认为加载状态
      relationNodes: [], // 关系图节点数据
      relationEdges: [] // 关系图边数据
    }
  },
  computed: {
    // 处理后的联系人列表
    processedContactList() {
      if (!this.contactList || this.contactList.length === 0) {
        return [];
      }
      return this.contactList.map(item => ({
        id: item.id || '',
        name: item.name || '未命名',
        phone: item.phoneNumber || '',
        img: item.avatarUrl || 'https://img1.baidu.com/it/u=1016138010,1907110459&fm=253&fmt=auto&app=138&f=JPEG?w=300&h=300',
        nickname: item.nickname || '',
        company: item.companyName || '',
        email: item.email || '',
        remark: item.remark || ''
      }));
    }
  },
  onLoad() {
    let sysInfo;
    // #ifdef MP-WEIXIN
    sysInfo = uni.getWindowInfo ? uni.getWindowInfo() : uni.getSystemInfoSync();
    // #endif
    // #ifndef MP-WEIXIN
    sysInfo = uni.getSystemInfoSync();
    // #endif
    this.statusBarHeight = sysInfo.statusBarHeight || 20;
  },
  // 监听页面显示
  onMounted() {
    // 页面加载时直接获取联系人列表
    this.fetchContactList();
  },
  onShow() {
    // 根据当前tab刷新对应内容
    if (this.tabIndex === 0) {
      this.fetchContactList();
    } else if (this.tabIndex === 1) {
      this.refreshRelationGraph();
      this.$refs.groupTabRef && this.$refs.groupTabRef.fetchGroupList && this.$refs.groupTabRef.fetchGroupList();
    } else if (this.tabIndex === 2) {
      this.$refs.tagTabRef && this.$refs.tagTabRef.fetchTagGroupList && this.$refs.tagTabRef.fetchTagGroupList();
    }
  },

  // 监听页面就绪状态
  onReady() {
  },

  onPullDownRefresh() {
    // 下拉刷新，根据当前tab刷新对应内容
    if (this.tabIndex === 0) {
      this.fetchContactList();
    } else if (this.tabIndex === 1) {
      // 群组tab，调用group-tab子组件的刷新方法
      this.$refs.groupTabRef && this.$refs.groupTabRef.fetchGroupList && this.$refs.groupTabRef.fetchGroupList();
    } else if (this.tabIndex === 2) {
      // 标签tab，调用tag-tab子组件的刷新方法
      this.$refs.tagTabRef && this.$refs.tagTabRef.fetchTagGroupList && this.$refs.tagTabRef.fetchTagGroupList();
    }
    // 结束下拉刷新动画
    setTimeout(() => {
      uni.stopPullDownRefresh();
    }, 300);
  },
  methods: {
    // 获取联系人列表
    async fetchContactList() {
      this.loading = true;
      try {
        const res = await ContactApi.queryContacts({});
        if (res.code === 0 && res.data) {
          // 先清空列表
          this.contactList = [];
          // 等待DOM更新
          await this.$nextTick();
          // 设置新数据
          this.contactList = res.data;
        } else {
          uni.showToast({
            title: '获取联系人失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取联系人列表失败', error);
        uni.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none'
        });
      } finally {
        // 延迟结束加载状态
        setTimeout(() => {
          this.loading = false;
          uni.stopPullDownRefresh();
        }, 100);
      }
    },

    // 切换Tab
    changeTab(index) {
      this.tabIndex = index;

      // 如果切换到群组标签页，检查是否需要刷新关系图
      if (index === 1) {
        this.refreshRelationGraph();
      }
    },

    // 刷新关系图组件
    refreshRelationGraph() {
      // 如果当前不在群组标签页，则不需要刷新
      if (this.tabIndex !== 1) {
        return;
      }

      this.$nextTick(() => {
        const relationGraphRef = this.$refs.relationGraphRef;
        if (relationGraphRef && typeof relationGraphRef.refresh === 'function') {
          console.log('调用关系图组件刷新');
          relationGraphRef.refresh();
        } else {
          // 如果组件还没准备好，延迟重试
          console.log('关系图组件未准备好，延迟重试');
          setTimeout(() => {
            const retryRef = this.$refs.relationGraphRef;
            console.log('延迟重试检查关系图组件:', {
              exists: !!retryRef,
              hasRefreshMethod: retryRef && typeof retryRef.refresh === 'function',
              refreshType: retryRef ? typeof retryRef.refresh : 'undefined'
            });

            if (retryRef && typeof retryRef.refresh === 'function') {
              console.log('延迟调用关系图组件刷新');
              retryRef.refresh();
            } else {
              console.log('延迟重试后仍然无法找到关系图组件的refresh方法');
            }
          }, 500);
        }
      });
    },

    // 点击联系人
    onContactClick(item) {
      uni.navigateTo({
        url: `/pages/contact/detail?id=${item.id}`
      })
    },

    // 添加联系人
    onAddContact() {
      uni.navigateTo({
        url: '/pages/contact/edit'
      })
    },

    handleNodeClick(params) {
      if (params.dataType === 'node') {
        uni.showToast({
          title: `点击了：${params.data.name}`,
          icon: 'none'
        });
      }
    }
  }
}
</script>

<style lang="scss">
.status-bar {
  width: 100%;
  background: #fff;
}

.nav-header {
  height: 56px;
  flex-shrink: 0;
  width: 100%;
  background: #fff;
  font-size: 20px;
  font-weight: bold;
  color: #333;
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid #f0f0f0;
  z-index: 10;
}

.page-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  /* 去除 height: 100% 避免多余滚动 */
  background-color: #f8f9fc;
  background-image: linear-gradient(to bottom, #f4f6ff, #f8f9fc);
  margin: 0;
  box-sizing: border-box;
  overflow: hidden;
}

/* 固定顶部区域 */
.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background-color: #f8f9fc;
  background-image: linear-gradient(to bottom, #f4f6ff, #f8f9fc);
}

/* 可滚动内容区域 */
.scrollable-content {
  overflow-y: auto;
  overflow-x: hidden;
  padding-top: 10px;
  /* 为固定顶部留出空间，动态计算 */
  margin-top: calc(var(--status-bar-height, 0px) + 56px + 50px);
  /* 简化高度控制，让内容自然撑开 */
  min-height: auto;
}

/* 微信小程序专用高度修正 */
/* #ifdef MP-WEIXIN */
.page-container {
  /* 在微信小程序中不使用vh单位，依赖父容器的flex布局 */
  min-height: auto;
}

.scrollable-content {
  /* 简化高度控制，让内容自然撑开 */
  min-height: auto;
}
/* #endif */

/* Tab标题栏样式优化 */
.tab-header {
  display: flex;
  background-color: #fff;
  height: 50px;
  // 去除圆角和阴影
  border-radius: 0;
  margin: 0;
  box-shadow: none;
  overflow: hidden;
  width: 100%;

  .tab-item {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    color: #666;
    position: relative;
    transition: all 0.3s ease;

    &.active {
      color: #2B7FF3;
      font-weight: 600;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 40px;
        height: 3px;
        background: linear-gradient(90deg, #2B7FF3, #5A9CFF);
        border-radius: 3px;
        box-shadow: 0 2px 4px rgba(43, 127, 243, 0.3);
      }
    }

    &:active {
      background-color: rgba(43, 127, 243, 0.05);
      transform: scale(0.98);
    }
  }
}

.content-area {
  flex: 1;
  // 去除左右边距和圆角
  margin: 0;
  background: #fff;
  border-radius: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  /* 去除 height: calc(100vh - 120px) 避免多余滚动 */
  box-shadow: none;
  width: 100%;
}

/* 加载和空状态样式 */
.loading-container, .empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #8e8e93;
  font-size: 14px;
}

.empty-container {
  .add-btn {
    margin-top: 20px;
    background: linear-gradient(135deg, #2B7FF3, #5A9CFF);
    color: #fff;
    font-size: 14px;
    padding: 6px 20px;
    border-radius: 20px;
    border: none;
    box-shadow: 0 4px 12px rgba(43, 127, 243, 0.25);
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.95);
      box-shadow: 0 2px 8px rgba(43, 127, 243, 0.4);
    }
  }
}

.relation-map {
  display: flex;
  flex-direction: column;
  /* 去除 height: 100% 让内容自然撑开 */
  width: 100%;
  min-height: 500px;
  background: #fff;
}

/* 保留原有样式 */
.address-book {
  flex: 1;
  /* 去除 height: 100% 让内容自然撑开 */
  overflow: hidden;
}

/* 添加悬浮按钮样式 */
.floating-btn {
  position: fixed;
  right: 30rpx;
  bottom: 160rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #2B7FF3, #5A9CFF);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 6rpx 20rpx rgba(43, 127, 243, 0.35);
  z-index: 100;
  transition: all 0.3s ease;

  .btn-icon {
    color: #fff;
    font-size: 50rpx;
    font-weight: 300;
    text-shadow: 0 1px 3px rgba(0,0,0,0.1);
  }

  &:active {
    transform: scale(0.9);
    box-shadow: 0 4rpx 16rpx rgba(43, 127, 243, 0.5);
  }
}

.cancel-btn, .confirm-btn {
  flex: 1;
  text-align: center;
  padding: 24rpx 0;
  font-size: 16px;
  font-weight: 500;
  border-radius: 12rpx;
  margin: 0 4rpx;
  // 让按钮看起来更像按钮
  box-sizing: border-box;
  user-select: none;
}
.cancel-btn {
  background-color: #f0f2f5;
  color: #666;
}
.confirm-btn {
  background: linear-gradient(135deg, #2B7FF3, #5A9CFF);
  color: #fff;
  box-shadow: 0 4rpx 12rpx rgba(43, 127, 243, 0.25);
}
.cancel-btn:active, .confirm-btn:active {
  opacity: 0.8;
}
</style>